package com.yonyou.crm.base.attr.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yonyou.crm.base.attr.entity.AttrBVO;
import com.yonyou.crm.base.attr.entity.AttrVO;
import com.yonyou.crm.common.biz.service.BaseBizServiceImpl;
import com.yonyou.crm.common.enumeration.service.EnumBizServiceImpl;
import com.yonyou.crm.common.exception.CrmBusinessException;
import com.yonyou.crm.common.field.handler.FieldRelationHandler;
import com.yonyou.crm.common.field.relation.EnumFieldRelation;
import com.yonyou.crm.common.field.relation.FieldRelation;
import com.yonyou.crm.common.page.entity.Page;
import com.yonyou.iuap.context.InvocationInfoProxy;

@Service
public class AttrBizServiceImpl extends BaseBizServiceImpl<AttrVO> {

	@Autowired
	private AttrBBizServiceImpl bService;

	@Autowired
	private EnumBizServiceImpl enumService;
	
	/**
	 * 分页查询
	 * @param page
	 * @param paraMap
	 * @return
	 */
	public Page<AttrVO> getPage(Page<AttrVO> page, Map<String, Object> paraMap) {
		
		Page<AttrVO> rPage = null;
		if (paraMap == null) {
			paraMap = new HashMap<String, Object>();
		}
		
		paraMap.put("tenantId", InvocationInfoProxy.getTenantid());
		
		rPage = super.pageSelect(AttrVO.class, page, paraMap.keySet().toArray(new String[0]), paraMap.values().toArray(new Object[0]));
		
		trans(rPage.getData());
		
		return rPage;
		
	}
	
	/**
	 * 列表记录详情
	 * @param id
	 * @return
	 */
	public AttrVO getPageDetail(Long id) {
		AttrVO vo = (AttrVO)dao.selectOne(AttrVO.class, "pageAttrDetail", id);
		trans(Arrays.asList(vo));
		return vo;
	}
	
	@Override
	protected void beforeSaveVO(AttrVO vo) {
		
		int count = getCountByName(vo.getId(), vo.getName());
		if (count > 0) {
			throw new CrmBusinessException("名称和其他属性重复，保存失败。");
		}
		
		super.beforeSaveVO(vo);
	}

	@Override
	protected void afterSaveVO(AttrVO vo) {
		super.afterSaveVO(vo);
			
		//保存属性值
		bService.batchInsertVO(vo.getId(), vo.getValueList());
	}

	@Override
	protected void beforeUpdateVO(AttrVO vo) {
		
		int count = getCountByName(vo.getId(), vo.getName());
		if (count > 0) {
			throw new CrmBusinessException("名称和其他属性重复，保存失败。");
		}
		
		super.beforeUpdateVO(vo);
	}

	@Override
	protected void afterUpdateVO(AttrVO vo) {
		super.afterUpdateVO(vo);
				
		//修改属性值
		bService.batchUpdateVO(vo.getId(), vo.getValueList());
	}

	public String batchDeleteByIDs(Class<AttrVO> clazz, String[] ids) {
		
		if (ids == null || ids.length == 0) {
			return "";
		}
		
		Set<String> idSet = new HashSet<String>();
		for (String id : ids) {
			idSet.add(id);
		}
		
		int totalCount = idSet.size();
		
		StringBuffer reasonBuffer = new StringBuffer("【");
		
		//是否属性组引用
		List<Map<String, Object>> attrList = getAttrGroupRefAttrList(idSet.toArray(new String[0]));
		
		if (attrList != null && attrList.size() > 0) {
			
			for (Map<String, Object> map : attrList) {
				
				reasonBuffer.append(map.get("name"));
				reasonBuffer.append(",");

				String typeId = map.get("id").toString();
				//被属性组引用的属性不能删除
				idSet.remove(typeId);
			}
			reasonBuffer.delete(reasonBuffer.length()-1, reasonBuffer.length());
			reasonBuffer.append("】属性被属性组引用，不可删除！");
		}
		
		int successCount = idSet.size();
		int failCount = totalCount - idSet.size();
		String message = failCount == 0 ? "成功" + successCount + "条。" : "成功" + successCount + "条，失败" + failCount + "条。\n失败原因：" + reasonBuffer.toString();
		
		if (successCount > 0) {
			
			bService.batchDeleteVO(idSet.toArray(new String[0]));
			super.batchDeleteByIDs(clazz, idSet.toArray(new String[0]));
		}
		
		return message;
	}

	/**
	 * 批量停启用属性
	 * @param ids
	 * @param enableState
	 */
	public void batchUpdateEnableState(String[] ids, Integer enableState) {
		
		Map<String, Object> enableParaMap = new HashMap<String, Object>();
		enableParaMap.put("ids", ids);
		enableParaMap.put("enableState", enableState);
		enableParaMap.put("enableUserId", new Long(InvocationInfoProxy.getParameter("id")));
		enableParaMap.put("enableTime", new Date());
				
		dao.updateSql(AttrVO.class, "batchUpdateEnableState", enableParaMap);
	}

	/**
	 * 根据名称查询数量
	 * @param id
	 * @param name
	 * @return
	 */
	public int getCountByName(Long id, String name) {
		Map<String, Object> paraMap = new HashMap<String, Object>();
		paraMap.put("id", id);
		paraMap.put("name", name);
		paraMap.put("tenantId", InvocationInfoProxy.getTenantid());
		return dao.countAll(AttrVO.class, "getCountByName", paraMap);
	}
	
	/**
	 * 校验属性是否被属性组引用
	 * @param attrIds
	 * @return
	 */
	public List<Map<String, Object>> getAttrGroupRefAttrList(String[] ids) {
		return dao.selectList(AttrVO.class, "getAttrGroupRefAttrList", ids);
	}
	
	/**
	 * 属性参照列表
	 * @return
	 */
	public List<AttrVO> getRefList() {
		return dao.selectVoList(AttrVO.class, "getRefList", null);
	}
	
	/**
	 * 根据id获取名称，逗号分隔
	 * @param ids
	 * @return
	 */
	public String getNamesByIds(Long[] ids) {
		Map<String, Object> para = new HashMap<String, Object>();
		para.put("ids", ids);
		return (String)dao.selectOne(AttrVO.class, "getNamesByIds", para);
	}
	
	public List<AttrVO> trans(List<AttrVO> voList) {
		
		if (voList != null && voList.size() > 0) {
			
			List<FieldRelation<AttrVO>> relations = new ArrayList<FieldRelation<AttrVO>>();
			relations.add(new EnumFieldRelation<AttrVO>(AttrVO.class, "enableState", "enableStateName", enumService, "enable_state"));
			new FieldRelationHandler<AttrVO>().handler(voList, relations);
		
			for (AttrVO vo : voList) {
				
				if (vo != null && vo.getValueList() != null && vo.getValueList().size() > 0) {
					
					List<FieldRelation<AttrBVO>> bRelations = new ArrayList<FieldRelation<AttrBVO>>();
					bRelations.add(new EnumFieldRelation<AttrBVO>(AttrBVO.class, "enableState", "enableStateName", enumService, "enable_state"));
					new FieldRelationHandler<AttrBVO>().handler(vo.getValueList(), bRelations);
				}
			}
		
		}

		return voList;
	}
}
